<?php
/**
 * @package PHPKit.
 * @author: mawenpei
 * @date: 2016/11/24
 * @time: 18:36
 */
namespace HuoKit\JobMan\Utility;

class TickTable extends \SplHeap
{
    public static $instance;

    public static function getInstance()
    {
        if(!static::$instance){
            static::$instance = new TickTable();
        }
        return static::$instance;
    }

    protected function compare($val1,$val2)
    {
        if($val1["tick"] === $val2["tick"]) return 0;
        return $val1["tick"] < $val2["tick"]?1:-1;
    }

    public static function set_task($sec_list,$task){
        $time = time();
        foreach ($sec_list as $sec) {
            if($sec > 60){
                static::getInstance()->insert(array("tick"=>$sec,"task"=>$task));
            }else{
                static::getInstance()->insert(array("tick"=>$time+$sec,"task"=>$task));
            }
        }
    }

    public static function get_task(){
        $time = time();
        $ticks = array();
        while(static::getInstance()->valid()){
            $data = static::getInstance()->extract();
            if($data["tick"] > $time){
                static::getInstance()->insert($data);
                break;
            }else{
                $ticks[] = $data["task"];
            }
        }
        return $ticks;
    }
}